/**
 * 송수신 내용 표시
 * 메시지를 전송할 클라이언트 선택(귓속말)
 */

package network;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MultiChatClient extends JFrame implements Runnable {

	Socket socket = null;
	MultiChatClientThread mcct = null;
	StringBuilder data = new StringBuilder();
	String comm;
	boolean log =false;
	String user;
	DefaultListModel<String> model = new DefaultListModel<String>();
	
	Vector<String> clientList = new Vector<>();
	
	JTextField userID;
	JList list;
	JTextField message;
	private JButton btnCon;
	private JButton btnDis;
	private JButton btnSend;
	
	
	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JPanel panel_2;
	JComboBox comboBox;
	private JPanel panel_3;
	private JPanel panel_4;
	private JButton btnNewButton_3;
	private JScrollPane scrollPane;
	private JScrollPane scrollPane_1;
	private JTextPane result;
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_1;
	private JPanel panel_5;
	private JLabel lblNewLabel_2;
	private JLabel lblNewLabel_3;
	private JPanel panel_6;
	private JTextField serverIP;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MultiChatClient frame = new MultiChatClient();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MultiChatClient() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				
				
				
			}
		});
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 563, 342);
		contentPane = new JPanel();
		contentPane.setBackground(Color.GRAY);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_2(), BorderLayout.SOUTH);
		contentPane.add(getPanel_3(), BorderLayout.CENTER);
		contentPane.add(getPanel_4(), BorderLayout.WEST);
		
		try {
			setTitle(InetAddress.getLocalHost().getHostAddress());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			socket= new Socket(serverIP.getText(),4444);
			mcct = new MultiChatClientThread(this, socket);
			mcct.start();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public void serverConnect() {
		comm = "login";
		user = userID.getText();
		Thread t = new Thread(this);
		t.start();
	}

	public void serverDisconnect() {
		comm = "logout";
		try {
			SocketData soc = new SocketData(comm, user, "로그아웃 되었습니다.", null);
			mcct.send.writeObject(soc);
			dataSet(soc);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		

//		SocketData sd = new SocketData("logout", userID.getText(), " 님이 로그아웃하셨네요", null);
//		mcct.sendMsg(sd);
		
		
	}

	public void sendMsg() {
		comm = "message";
		try {
			SocketData soc = new SocketData(comm, user,
					message.getText(), null);
			mcct.sendMsg(soc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void changeID(){
		
		comm = "change";
		try {
			SocketData soc = new SocketData(comm, user, userID.getText() , null);
			mcct.send.writeObject(soc);
		} catch (Exception e) {
			e.printStackTrace();
		}
		user = userID.getText();
	}

	public String getUser() {
		return user;
	}

	// 오버로딩(다형화) dataSet
	public void dataSet(SocketData sd) {// JTextPane에 문자열을 추가하기 위해서
		String icon = "";
		if(sd.getIndex() >0){
			icon = "<img src = 'file:\\H:\\JAVA\\ht\\1403\\ori"+sd.getIndex()+".gif' width='100' heigth='100'><br>";
			data.append(icon);
		}
		
		
		data.append(sd.getUser() + " : " + sd.getMessage());
		data.append("<br/>");
		result.setText(data.toString());
	}

	// 오버로딩(다형화) dataSet
	public void dataSet(String d) {
		data.append(d);
		data.append("<br/>");
		result.setText(data.toString());
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getPanel_1(), BorderLayout.EAST);
			panel.add(getPanel_5(), BorderLayout.WEST);
			panel.add(getPanel_6(), BorderLayout.CENTER);
		}
		return panel;
	}

	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
			panel_1.add(getBtnCon());
			panel_1.add(getBtnDis());
		}
		return panel_1;
	}

	private JButton getBtnCon() {
		if (btnCon == null) {
			btnCon = new JButton("연결");
			btnCon.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					btnCon.setEnabled(false);
					btnDis.setEnabled(true);
					log = true;
					serverConnect();
				}
			});
		}
		return btnCon;
	}

	private JButton getBtnDis() {
		if (btnDis == null) {
			btnDis = new JButton("종료");
			btnDis.setEnabled(false);
			btnDis.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					btnCon.setEnabled(true);
					btnDis.setEnabled(false);
					log = false;
					serverDisconnect();
				}
			});
		}
		return btnDis;
	}

	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.setLayout(new BorderLayout(0, 0));
			panel_2.add(getMessage());
			panel_2.add(getBtnSend(), BorderLayout.EAST);
			panel_2.add(getComboBox(), BorderLayout.WEST);
		}
		return panel_2;
	}

	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if(!log){
						JOptionPane.showMessageDialog(null, "서버에 연결되어 있지 않았습니다.");
						return;
					}
					
					if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
						sendMsg();
						message.setText("");
					} else if (arg0.getKeyCode() == KeyEvent.VK_ESCAPE) {
						message.setText("");
						
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}

	private JButton getBtnSend() {
		if (btnSend == null) {
			btnSend = new JButton("전송");
			btnSend.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					if(!log){
						JOptionPane.showMessageDialog(null, "서버에 연결되어 있지 않았습니다.");
						return;
					}
//					if(user != userID.getText()){
//						int yn = JOptionPane.showConfirmDialog(null, "닉네임이 변경되었습니다. 닉네임을 바꾸시겠습니까?");
//						if(yn == JOptionPane.YES_OPTION){
//							changeID();
//						}
//						return;
//					}
					sendMsg();
					message.setText("");
				}
			});
		}
		return btnSend;
	}

	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setPreferredSize(new Dimension(60,30));

			comboBox.addItem(new ImageIcon("H:\\JAVA\\ht\\1403\\ori0.gif"));
			comboBox.addItem(new ImageIcon("H:\\JAVA\\ht\\1403\\ori11.png"));  // gif는 안된다
			comboBox.addItem(new ImageIcon("H:\\JAVA\\ht\\1403\\ori2.gif"));
			comboBox.addItem(new ImageIcon("H:\\JAVA\\ht\\1403\\ori3.gif"));
			comboBox.addItem(new ImageIcon("H:\\JAVA\\ht\\1403\\ori4.gif"));
			comboBox.addItem(new ImageIcon("H:\\JAVA\\ht\\1403\\ori5.gif"));
			
		}
		return comboBox;
	}

	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setLayout(new BorderLayout(0, 0));
			panel_3.add(getScrollPane_1_1(), BorderLayout.CENTER);
		}
		return panel_3;
	}

	private JPanel getPanel_4() {
		if (panel_4 == null) {
			panel_4 = new JPanel();
			panel_4.setLayout(new BorderLayout(0, 0));
			panel_4.add(getBtnNewButton_3(), BorderLayout.SOUTH);
			panel_4.add(getScrollPane(), BorderLayout.CENTER);
		}
		return panel_4;
	}

	private JButton getBtnNewButton_3() {
		if (btnNewButton_3 == null) {
			btnNewButton_3 = new JButton("파일전송");
			btnNewButton_3.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					SocketData sd = new SocketData("fileTrans",userID.getText(),"파일전송",null);
					mcct.sendMsg(sd);
					
					

				}
			});
		}
		return btnNewButton_3;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getList());
			scrollPane.setColumnHeaderView(getLblNewLabel());
		}
		return scrollPane;
	}

	private JList getList() {
		if (list == null) {
			list = new JList(model);
		}
		return list;
	}

	private JScrollPane getScrollPane_1_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setViewportView(getResult());
			scrollPane_1.setColumnHeaderView(getLblNewLabel_1());
		}
		return scrollPane_1;
	}

	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setFont(new Font("맑은 고딕", Font.PLAIN, 12));
			result.setContentType("text/html");
		}
		return result;
	}

	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("접속자목록");
			lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel;
	}

	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("채 팅");
			lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel_1;
	}

	private JTextField getTextField_2() {
		if (userID == null) {
			userID = new JTextField();
			userID.setText("이몸");
			userID.setColumns(10);
		}
		return userID;
	}

	private JPanel getPanel_5() {
		if (panel_5 == null) {
			panel_5 = new JPanel();
			panel_5.setLayout(new BorderLayout(0, 0));
			panel_5.add(getTextField_2(), BorderLayout.CENTER);
			panel_5.add(getLblNewLabel_2(), BorderLayout.WEST);
		}
		return panel_5;
	}

	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel("  ID  ");
			lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel_2;
	}

	private JLabel getLblNewLabel_3() {
		if (lblNewLabel_3 == null) {
			lblNewLabel_3 = new JLabel("  IP  ");
			lblNewLabel_3.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return lblNewLabel_3;
	}

	private JPanel getPanel_6() {
		if (panel_6 == null) {
			panel_6 = new JPanel();
			panel_6.setLayout(new BorderLayout(0, 0));
			panel_6.add(getServerIP(), BorderLayout.CENTER);
			panel_6.add(getLblNewLabel_3(), BorderLayout.WEST);
		}
		return panel_6;
	}

	private JTextField getServerIP() {
		if (serverIP == null) {
			serverIP = new JTextField();
			serverIP.setText("192.168.10.130");
			serverIP.setColumns(10);
		}
		return serverIP;
	}
}
